package com.liang.filter;

import com.liang.util.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
//        获取userSession，通过判断user是否存在过滤
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        Object user = session.getAttribute(Constant.USER_SESSION);
//        用户不存在，重定向到登录页面
        if(user ==null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return; //重定向禁止原请求操作
        }
//        执行请求后续操作
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}
